package org.surelink.radius.middleware.auth;

import org.surelink.radius.cache.GroupCache;
import org.surelink.radius.cache.UserCache;
import org.surelink.radius.middleware.AuthMiddleware;
import org.surelink.radius.model.User;
import org.apache.log4j.Logger;
import org.surelink.radius.constant.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.tinyradius.packet.AccessRequest;
import org.tinyradius.packet.RadiusPacket;

public class AuthMacMiddleware implements AuthMiddleware
{
    private static final Logger log = Logger.getLogger(AuthMacMiddleware.class);

    @Autowired
    private UserCache userCache;

    @Autowired
    private GroupCache groupCache;

    public RadiusPacket onAuth(User user,AccessRequest request, RadiusPacket response)
			throws Exception {

        if(log.isInfoEnabled())
            log.info("start AuthMacMiddleware ...");

        String macaddr = request.getMacAddress();
        String userBmacMeta = userCache.getUserMeta(user.getUserName(), Constant.USER_BIND_MAC.value());
        String groupBmacMeta = groupCache.getGroupMeta(user.getGroupName(), Constant.GROUP_BIND_MAC.value());

        boolean _bindMac = groupBmacMeta != null ? "1".equals(groupBmacMeta) : false;
        boolean bindMac = userBmacMeta != null ? "1".equals(userBmacMeta) : _bindMac;

        if (bindMac) {
            String userMac = userCache.getUserMeta(user.getUserName(), Constant.USER_MAC_ADDR.value());
            if (userMac == null) {
                userCache.setUserMeta(user.getUserName(),Constant.USER_MAC_ADDR.value(),macaddr);
            } else {
                if (!userMac.equals(macaddr))
                {
                    response.setPacketType(RadiusPacket.ACCESS_REJECT);
                    response.addAttribute("Reply-Message", "用户MAC地址不匹配");
                    return response;
                }
            }
        }

		return response;
	}




}
